<template>
  <a-row>
    <div class="total-table-container">
      <a-row style="margin-bottom: 8px;">
        <a-col :span="4">
          <a-button class="editable-add-btn" type="primary" @click="toAddPage"
            >新建</a-button
          >
        </a-col>
        <a-col :span="2" push="18" style="text-align: right;">
          <ExportFile
            :fetch="getDownloadData"
            :fields="jsonFields"
            name="downloadFile.xls"
          >
            <a-button
              class="editable-add-btn"
              type="primary"
              :loading="iconLoading"
              >导出</a-button
            >
          </ExportFile>
        </a-col>
      </a-row>

      <a-row>
        <a-table
          :columns="tableColumns"
          :data-source="tableDataLists"
          :scroll="{ x: 1200 }"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          :customRow="clickSingleRow"
          :pagination="paginationOpt"
          :loading="isLoading"
          bordered
          @change="handleTableChange"
        >
          <template slot="leftExt" slot-scope="text, record, index">
            <a-tooltip placement="right" v-if="record.operateStatus !== 100">
              <template slot="title">
                废除此单
              </template>
              <a-icon
                type="close-circle"
                @click.stop="confirmWasteRepairDone(record)"
              />
            </a-tooltip>
          </template>
          <template slot="operateStatus" slot-scope="text, record, index">
            <div class="editable-row-operations">
              <template v-if="record.operateStatus === 2">
                <a-button type="primary" @click.stop="confirmOrder(record)"
                  >确认收货</a-button
                >
              </template>
              <template v-else-if="record.operateStatus === 3">
                <a-button type="primary" @click.stop="confirmAssign(record)"
                  >指派</a-button
                >
              </template>
              <template v-else-if="record.operateStatus === 4">
                <a-button type="primary" @click.stop="confirmOrder(record)"
                  >确认收货</a-button
                >
              </template>
              <template v-else-if="record.operateStatus === 5">
                <a-button type="primary" @click.stop="confirmFix(record)"
                  >开始维修</a-button
                >
              </template>
              <template v-else-if="record.operateStatus === 6">
                <a-button type="primary" @click.stop="confirmFixDone(record)"
                  >维修完成</a-button
                >
                <a-button type="primary" @click.stop="confirmAssign(record)"
                  >指派</a-button
                >
              </template>
              <template v-else-if="record.operateStatus === 8">
                <a-button type="primary" @click.stop="confirmRepairDone(record)"
                  >返修完成</a-button
                >
                <a-button type="primary" @click.stop="confirmAssign(record)"
                  >指派</a-button
                >
              </template>
              <template v-else-if="record.operateStatus === 11">
                <a-button type="primary" @click.stop="confirmOrder(record)"
                  >确认收货</a-button
                >
              </template>
            </div>
          </template>
        </a-table>
      </a-row>
    </div>

    <a-modal
      v-model="isAssignShow"
      title="指派"
      class="dispatch-modal"
      okText="确定"
      cancelText="取消"
      @ok="assignModalOKBtn"
      @cancel="assignModalCloseBtn"
    >
      <a-form-model
        ref="assignForm"
        :model="assignForm"
        :rules="assignFormRules"
        v-bind="modelFormlayout"
      >
        <a-form-model-item label="指派工程师" prop="repairAssignValue">
          <a-select
            v-model="assignForm.repairAssignValue"
            style="width: 100%;"
            allow-clear
            show-search
            :options="assignLists"
            :filter-option="filterAssignUsername"
          >
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
      v-model="isFixDoneShow"
      title="维修结果"
      class="dispatch-modal"
      okText="确定"
      cancelText="取消"
      @ok="confirmFixDoneBtn"
      @cancel="confirmFixDoneCloseBtn"
    >
      <a-form-model
        ref="fixDoneForm"
        :model="fixDoneForm"
        :rules="fixDoneRules"
        v-bind="modelFormlayout"
      >
        <a-form-model-item label="指派工程师" prop="assign">
          <a-select
            v-model="fixDoneForm.assign"
            style="width: 100%;"
            allow-clear
            show-search
            :options="assignLists"
            :filter-option="filterAssignUsername"
          >
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="故障类型" prop="reason">
          <a-select
            v-model="fixDoneForm.reason"
            style="width: 100%;"
            allow-clear
            :options="faultTypeLists"
            @change="faultTypeHandle"
          ></a-select>
        </a-form-model-item>
        <a-form-model-item label="故障细分" prop="faultSubdivision">
          <a-select
            v-model="fixDoneForm.faultSubdivision"
            style="width: 100%;"
            allow-clear
            :options="faultTypeDetailLists"
          ></a-select>
        </a-form-model-item>
        <a-form-model-item label="备注信息" prop="remark">
          <a-textarea
            v-model="fixDoneForm.remark"
            style="width: 100%;"
            :autoSize="{ minRows: 2, maxRows: 4 }"
            allow-clear
          ></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
      v-model="isFinishShow"
      title="返修结果"
      class="dispatch-modal"
      okText="确定"
      cancelText="取消"
      @ok="confirmFinishBtn"
      @cancel="confirmFinishCloseBtn"
    >
      <a-form-model
        ref="finishForm"
        :model="finishForm"
        :rules="finishRules"
        v-bind="modelFormlayout"
      >
        <a-form-model-item label="维修结果" prop="resultType">
          <a-radio-group
            v-model="finishForm.resultType"
            :options="repairResultTypeLists"
            @change="resultTypeHandle"
          >
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          v-show="finishForm.resultType == 2"
          label="快递公司"
          prop="returnExpressCompany"
        >
          <a-input v-model="finishForm.returnExpressCompany" allow-clear />
        </a-form-model-item>
        <a-form-model-item
          v-show="finishForm.resultType == 2"
          label="快递单号"
          prop="returnExpressNumber"
        >
          <a-input v-model="finishForm.returnExpressNumber" allow-clear />
        </a-form-model-item>
        <a-form-model-item
          v-show="finishForm.resultType == 2"
          label="原地址"
          prop="isOldAdr"
        >
          <a-switch
            v-model="finishForm.isOldAdr"
            @change="resultOldAdrHandle"
            allow-clear
          />
        </a-form-model-item>
        <a-form-model-item
          v-show="finishForm.resultType == 2"
          label="返修地址"
          prop="actualReturnAddress"
        >
          <a-input v-model="finishForm.actualReturnAddress" allow-clear />
        </a-form-model-item>
        <a-form-model-item label="备注信息" prop="remark">
          <a-textarea v-model="finishForm.remark" allow-clear />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
      v-model="isWasteShow"
      title="废单确认"
      class="dispatch-modal"
      okText="确定"
      cancelText="取消"
      @ok="confirmWasteBtn"
      @cancel="confirmWasteCloseBtn"
    >
      <a-form-model ref="wasteForm" :model="wasteForm" v-bind="modelFormlayout">
        <a-form-model-item label="备注信息" prop="wasterRemark">
          <a-textarea
            v-model="wasteForm.wasterRemark"
            :autoSize="{ minRows: 4, maxRows: 8 }"
            allow-clear
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-row>
</template>

<script>
import api from "@/server/userConfig";
import { buildLinkSelect, getRoleId, filterTableColumns } from "@/unit/tool";
import { RepairResultType } from "@/unit/constantValue";
import { columns } from "./tableConfig";
import { AssignRules, FixDoneRules, FinishRules } from "./rulesConfig";
import ExportFile from "vue-json-excel";

function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
    if (item.dataIndex != "operateStatus") {
      jsonFields[item.title] = item.dataIndex;
    }
  });
  return jsonFields;
}

export default {
  name: "HistoryOrderTable",
  props: {
    searchData: Object
  },
  components: {
    ExportFile
  },
  data() {
    return {
      userName: "",
      role: "",
      compId: "",
      tableColumns: [],
      tableDataLists: [],
      isLoading: false,
      rowRecord: "",
      modelFormlayout: {
        layout: "horizontal",
        labelAlign: "right",
        hideRequiredMark: true,
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      isAssignShow: false,
      assignFormRules: AssignRules,
      assignLists: [],
      assignForm: {
        repairAssignValue: ""
      },
      isFixDoneShow: false,
      fixDoneRules: FixDoneRules,
      faultTypeLists: [],
      faultTypeDetailLists: [],
      faultLinkSelect: {},
      fixDoneForm: {
        assign: "",
        reason: "",
        faultSubdivision: "",
        remark: ""
      },
      isFinishShow: false,
      finishRules: FinishRules,
      finishForm: {
        resultType: 1,
        remark: "",
        returnExpressCompany: "",
        returnExpressNumber: "",
        actualReturnAddress: "",
        isOldAdr: false
      },
      isWasteShow: false,
      wasteForm: {
        wasterRemark: ""
      },
      repairResultTypeLists: RepairResultType,

      paginationOpt: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 8, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showTotal: total => `共 ${total} 条`, // 显示总数
        // 点击分页时事件
        onChange: (current, size) => {
          let _this = this;
          this.getAllRepair({ pageNum: current }, "tableDataLists");
        }
      },
      iconLoading: false,
      jsonFields: buildJsonFields(columns)
    };
  },
  computed: {},
  watch: {
    searchData: function(newVal, oldVal) {
      let _this = this;
      _this.getData({ pageNum: 1 });
    }
  },
  created() {},
  mounted() {
    // 获取useInfo
    getRoleId(this);
    if (this.role == 17) {
      this.tableColumns = columns;
    } else {
      this.tableColumns = filterTableColumns(columns, ["leftExt"]);
    }
    this.getData({ pageNum: 1 });
    this.getAssignList({ companyId: this.compId }, "assignLists");
    this.getFaultSubdivision(
      { username: this.userName },
      "faultLinkSelect",
      "faultTypeLists",
      "faultTypeDetailLists"
    );
  },
  methods: {
    getData(parames) {
      this.getAllRepair(parames, "tableDataLists");
    },
    handleTableChange(pagination) {
      this.paginationOpt.current = pagination.current;
    },
    // Table 获取数据
    async getAllRepair(parames, key) {
      let _this = this;
      let { pageNum } = parames;
      let { isProcess, statusList, ...restparames } = _this.searchData;
      _this.isLoading = true;
      const res = await api.getAllRepair({
        pageNum,
        pageSize: _this.paginationOpt.defaultPageSize,
        username: isProcess ? _this.userName : "",
        statusList: statusList ? statusList.toString() : "",
        operateUsername: _this.userName,
        ...restparames
      });

      _this.isLoading = false;
      if (res.msgCode !== 0) {
        return;
      }

      this.paginationOpt.total = res.data.total;

      let newObj = res.data.rows;
      this[key] = newObj;
    },

    // 点击每一行的跳转;
    clickSingleRow(record, index) {
      return {
        on: {
          click: () => {
            // 实现跳转;
            window.open(`/#/productRepairDetail?id=${record.repairId}`);
          }
        }
      };
    },

    // 新建工单
    toAddPage() {
      window.open(`/#/newProductRepair`);
    },

    // 列表确认收货按钮
    confirmOrder(item) {
      let _this = this;
      this.$Modal.confirm({
        title: "是否确认收货?",
        onOk() {
          let { repairId, status } = item;
          _this.repairReceive({
            repairId,
            status,
            username: _this.userName,
            operator: _this.name
          });
        },
        onCancel() {}
      });
    },
    // 确认收货
    async repairReceive(params) {
      const res = await api.repairReceive({ ...params });
      if (res.msgCode === 0) {
        this.$message.success(res.msgDesc);
        this.getData({ pageNum: this.paginationOpt.current });
      } else {
        this.$message.error(res.msgDesc);
      }
    },

    // 列表指派按钮
    confirmAssign(item) {
      this.isAssignShow = true;
      this.rowRecord = item;
    },
    // 指派弹框ok按钮
    assignModalOKBtn() {
      let _this = this;
      _this.$refs["assignForm"].validate(valid => {
        if (valid) {
          let { repairId } = _this.rowRecord;
          let assignUsernameAry = _this.assignForm.repairAssignValue.split(",");
          _this.repairAssign({
            repairId,
            assignUsername: assignUsernameAry[1],
            assignOperator: assignUsernameAry[0],
            username: _this.userName,
            operator: _this.name
          });
        }
      });
    },
    // 指派弹框close按钮
    assignModalCloseBtn(item) {
      let _this = this;
      _this.$refs["assignForm"].resetFields();
    },
    // 返修指派
    async repairAssign(params) {
      const res = await api.repairAssign({ ...params });
      if (res.msgCode === 0) {
        this.$message.success(res.msgDesc);
        this.isAssignShow = false;
        this.$refs["assignForm"].resetFields();
        this.getData({ pageNum: this.paginationOpt.current });
      } else {
        this.$message.error(res.msgDesc);
      }
    },
    // 获取指派人
    async getAssignList(parames, key) {
      let _this = this;
      const res = await api.getAssignList({
        username: _this.userName,
        ...parames
      });
      if (res.msgCode !== 0) {
        return;
      }
      this[key] = buildSelectOption(res.data);
      function buildSelectOption(lists) {
        let _lists = [];
        _lists = lists.map((item, index) => {
          let { operator, username } = item;
          return {
            label: `${operator}  ${username}`,
            value: `${operator},${username}`
          };
        });
        return _lists;
      }
    },
    // 过滤指派人
    filterAssignUsername(input, option) {
      let str = input.replace(/\s*/g, "");
      let name = option.componentOptions.children[0].text;

      if (name == "" || name == undefined || str == "" || str == undefined) {
        return false;
      } else {
        let isMatch = name.indexOf(str) >= 0;
        return isMatch;
      }
    },

    // 列表开始维修按钮
    confirmFix(item) {
      let _this = this;
      this.$Modal.confirm({
        title: "是否开始维修?",
        onOk() {
          let { repairId, status } = item;
          _this.repairBeginMaintain({
            repairId,
            status,
            username: _this.userName,
            operator: _this.name
          });
        },
        onCancel() {}
      });
    },
    // 开始维修
    async repairBeginMaintain(params) {
      const res = await api.repairBeginMaintain({ ...params });
      if (res.msgCode === 0) {
        this.$message.success(res.msgDesc);
        this.getData({ pageNum: this.paginationOpt.current });
      } else {
        this.$message.error(res.msgDesc);
      }
    },

    // 列表维修完成按钮
    confirmFixDone(item) {
      this.isFixDoneShow = true;
      this.rowRecord = item;
    },
    // 维修完成弹框ok按钮
    async confirmFixDoneBtn() {
      let _this = this;
      _this.$refs["fixDoneForm"].validate(valid => {
        if (valid) {
          let { repairId, status } = _this.rowRecord;
          let { assign, ...restForm } = _this.fixDoneForm;
          let assignUsernameAry = assign.split(",");
          _this.repairMaintainFinish({
            repairId,
            status,
            username: _this.userName,
            operator: _this.name,
            ...restForm,
            assignUsername: assignUsernameAry[1],
            assignOperator: assignUsernameAry[0]
          });
        }
      });
    },
    // 维修完成弹框close按钮
    confirmFixDoneCloseBtn() {
      let _this = this;
      _this.$refs["fixDoneForm"].resetFields();
    },
    // 维修完成
    async repairMaintainFinish(params) {
      const res = await api.repairMaintainFinish({ ...params });
      if (res.msgCode === 0) {
        this.$message.success(res.msgDesc);
        this.isFixDoneShow = false;
        this.$refs["fixDoneForm"].resetFields();
        this.getData({ pageNum: this.paginationOpt.current });
      } else {
        this.$message.error(res.msgDesc);
      }
    },
    // 获取故障原因和故障细分数据
    async getFaultSubdivision(parames, objKey, lv1Key, lv2Key) {
      const res = await api.getFaultSubdivision({ ...parames });
      if (res.msgCode !== 0) {
        return;
      }
      this[objKey] = buildLinkSelect(
        res.data,
        "faultReason",
        "faultSubdivision"
      );
      this[lv1Key] = this[objKey].lv1;
      this[lv2Key] = [];
    },
    // 故障原因下拉操作
    faultTypeHandle(e) {
      let key = e;
      this.faultTypeDetailLists = this.faultLinkSelect.lv2[key];
      this.fixDoneForm.faultSubdivision = this.faultTypeDetailLists[0].value;
    },

    // 列表返修完成按钮
    confirmRepairDone(item) {
      this.isFinishShow = true;
      this.rowRecord = item;
    },
    // 返修完成弹框ok按钮
    confirmFinishBtn() {
      let _this = this;
      _this.$refs["finishForm"].validate(valid => {
        if (valid) {
          let { repairId, status } = _this.rowRecord;
          let { isOldAdr, ...restForm } = _this.finishForm;
          _this.repairFinish({
            repairId,
            status,
            username: _this.userName,
            operator: _this.name,
            ...restForm
          });
        }
      });
    },
    // 返修完成弹框close按钮
    confirmFinishCloseBtn() {
      let _this = this;
      _this.$refs["finishForm"].resetFields();
    },
    // 返修完成完成
    async repairFinish(params) {
      const res = await api.repairFinish({ ...params });
      if (res.msgCode === 0) {
        this.$message.success(res.msgDesc);
        this.$refs["finishForm"].resetFields();
        this.isFinishShow = false;
        this.getData({ pageNum: this.paginationOpt.current });
      } else {
        this.$message.error(res.msgDesc);
      }
    },
    // 返修结果选择操作
    resultTypeHandle(e) {
      let value = e.target.value;
      if (value !== 2) {
        for (const key in FinishRules) {
          if (Object.hasOwnProperty.call(FinishRules, key)) {
            FinishRules[key][0]["required"] = false;
          }
        }
        this.finishForm.returnExpressCompany = "";
        this.finishForm.returnExpressNumber = "";
        this.finishForm.actualReturnAddress = "";
      } else {
        for (const key in FinishRules) {
          if (Object.hasOwnProperty.call(FinishRules, key)) {
            FinishRules[key][0]["required"] = true;
          }
        }
      }
    },
    // 是否使用原地址
    resultOldAdrHandle(e) {
      let value = e;
      let { returnAddress } = this.rowRecord;
      if (value) {
        this.finishForm.actualReturnAddress = returnAddress;
      } else {
        this.finishForm.actualReturnAddress = "";
      }
    },

    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      if (_this.iconLoading == true) {
        return false;
      }
      let total = _this.paginationOpt.total;
      let pageSize = 300;
      let length = Math.ceil(total / pageSize);
      let newLists = [];
      _this.iconLoading = true;
      for (let i = 1; i <= length; i++) {
        let lists = await this.buildDownloadLists({
          pageNum: i,
          pageSize: pageSize
        });
        newLists.push(lists);
      }
      _this.iconLoading = false;
      return [].concat(...newLists);
    },

    async buildDownloadLists(parames) {
      let _this = this;
      let { pageNum, pageSize } = parames;
      let { isProcess, statusList, ...restparames } = _this.searchData;
      const res = await api.getAllRepair({
        pageNum,
        pageSize,
        username: isProcess ? _this.userName : "",
        statusList: statusList ? statusList.toString() : "",
        operateUsername: _this.userName,
        ...restparames
      });

      if (res.msgCode !== 0) {
        return;
      }

      let list = buildLists(res.data.rows);
      return list;

      function buildLists(lists) {
        return lists.map((item, index) => {
          try {
            let newItem = format(item);
            return newItem;
          } catch (e) {
            console.log(e);
          }
        });
      }

      function format(item) {
        if (item.repairNumber) {
          item.repairNumber = `'${item.repairNumber}'`;
        }
        if (item.status) {
          item.status = formatState(item.status);
        }
        return item;
      }

      function formatState(state) {
        switch (state) {
          case 2:
            return "返厂中";
          case 3:
            return "已收货";
          case 4:
            return "已指派";
          case 5:
            return "维修收货";
          case 6:
            return "维修中";
          case 8:
            return "维修完成";
          case 10:
            return "返修完成";
          case 11:
            return "维修中";
          case 100:
            return "已废单";
          default:
            break;
        }
      }
    },
    // 列表废单按钮
    confirmWasteRepairDone(item) {
      this.isWasteShow = true;
      this.rowRecord = item;
    },
    // 废单操作
    confirmWasteBtn() {
      let _this = this;
      _this.$refs["wasteForm"].validate(valid => {
        if (valid) {
          let { repairId } = _this.rowRecord;
          let { wasterRemark } = _this.wasteForm;
          _this.wasterRepair({
            repairId,
            username: _this.userName,
            name: _this.name,
            wasterRemark
          });
        }
      });
    },
    // 废单操作弹框close按钮
    confirmWasteCloseBtn() {
      let _this = this;
      _this.$refs["wasteForm"].resetFields();
    },
    // 废单接口
    async wasterRepair(params) {
      const res = await api.wasterRepair({ ...params });
      if (res.msgCode === 0) {
        this.$message.success("废单成功");
        this.$refs["wasteForm"].resetFields();
        this.isWasteShow = false;
        this.getData({ pageNum: this.paginationOpt.current });
      } else {
        this.$message.error("废单失败");
      }
    }
  }
};
</script>

<style lang="css" scoped>
@import "./style.css";
.itemWrap {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.itemWrap > .label {
  min-width: 90px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #373737;
  text-align: right;
}

.itemWrap > .separator {
  padding: 0px 4px;
}

.itemWrap > .content {
  width: 100%;
  padding: 0px 1px;
}
</style>
